<template>
  <el-scrollbar>
    <div class="w-100% min-w-800px">
      <div id="CpuMain" style="width: 100%; height: 400px" @mouseenter="pauseFetching" @mouseleave="resumeFetching" />
    </div>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { onMounted, ref, defineProps, onUnmounted } from "vue";
import * as echarts from "echarts";
import { getVirtualLog } from "@/api/virtual";

const props = defineProps(["ID"]);
const isPaused = ref(false);

const getFormattedDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

let myChart: echarts.ECharts | null = null;
let fetchInterval: NodeJS.Timeout | null = null;

onMounted(async () => {
  console.log(props.ID, "ID");
  const chartDom = document.getElementById("CpuMain");
  if (!chartDom) return;
  myChart = echarts.init(chartDom);

  // 初始化图表
  updateChart([]);
  // 第一次获取数据
  await GetOne();
  // 开始定时获取数据
  startFetching();
});

onUnmounted(() => {
  if (fetchInterval) {
    clearInterval(fetchInterval);
  }
});

const GetOne = async () => {
  const endTime = new Date();
  const startTime = new Date(endTime.getTime() - 10 * 60 * 1000); // 10 minutes ago
  const formattedStartTime = getFormattedDate(startTime);
  const formattedEndTime = getFormattedDate(endTime);
  const data = await getVirtualLog({
    id: props.ID,
    start_time: formattedStartTime,
    end_time: formattedEndTime
  });
  updateChart(data.data.data); // 更新图表数据
};
const updateChart = (data: any[]) => {
  if (!myChart) return;

  // 提取时间、CPU使用率和内存使用率
  const timeData = data.map(item => getFormattedDate(new Date(item.time)));
  const cpuUsageData = data.map(item => item.cpu_usage);
  const memoryUsageData = data.map(item => item.memory_usage);

  const option = {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["CPU使用情况", "内存使用情况"]
    },
    xAxis: {
      type: "category",
      data: timeData
    },
    yAxis: [
      {
        type: "value"
      }
    ],
    series: [
      {
        name: "CPU使用情况(%)",
        type: "line",
        data: cpuUsageData
      },
      {
        name: "内存使用情况(MB)",
        type: "line",
        data: memoryUsageData
      }
    ]
  };

  myChart.setOption(option);
};

const pauseFetching = () => {
  isPaused.value = true;
};

const resumeFetching = () => {
  isPaused.value = false;
};

const startFetching = () => {
  fetchInterval = setInterval(async () => {
    if (!isPaused.value) {
      try {
        const endTime = new Date();
        const startTime = new Date(endTime.getTime() - 10 * 60 * 1000); // 10 minutes ago
        const formattedStartTime = getFormattedDate(startTime);
        const formattedEndTime = getFormattedDate(endTime);
        const data = await getVirtualLog({
          id: props.ID,
          start_time: formattedStartTime,
          end_time: formattedEndTime
        });
        updateChart(data.data.data); // 更新图表数据
      } catch (error) {
        console.error("Failed to fetch data:", error);
      }
    }
  }, 10000);
};
</script>
